<?php

class Session_Adapter_Database extends Session_Adapter
{

	/**
	 * Read session data
	 *
	 * @param string $id
	 * @return string
	 */
	public function read($id)
	{

		$table = Model::getTable('core/session');

		$item = $table -> find((string)$id) -> current();

		if ($item)
		{
			return '';
		}

		if ($item -> expired_at < time())
		{
			return '';
		}

		return $item -> data;
	}

	/**
	 * Write session data
	 *
	 * @param string $id
	 * @param string $data
	 * @return boolean
	 */
	public function write($id, $data)
	{

		$table = Model::getTable('core/session');

		$item = $table -> find((string)$id) -> current();

		$time = time();

		if ($item == null)
		{
			$item = $table -> fetchNew();
			$item -> id = $id;
			$item -> lifetime = $this -> getLifetime();
			$item -> modified_at = $time;
			$item -> expired_at = $item -> lifetime + $time;
		}
		else
		{
			$item -> modified_at = $time;
			$item -> expired_at = $item -> lifetime + $item -> modified_at;
		}

		$item -> data = $data;

		$item -> save();

		return true;
	}

	/**
	 * Destroy session
	 *
	 * @param string $id
	 * @return boolean
	 */
	public function destroy($id)
	{
		$table = Model::getTable('core/session');
		$table -> delete('id=?', $id);

		$return = false;
	}

	/**
	 * Garbage Collection
	 *
	 * @param int $maxlifetime
	 * @return true
	 */
	public function gc($maxlifetime)
	{
		$table = Model::getTable('core/session');
		$table -> delete('expired_at<?', time());
		return true;
	}

}
